"use client";

import Navigation from "@/components/navigation/navigation";
import * as React from "react";
import { useEffect, useState } from "react";
import store from "@/store/store";

export default function LocaleLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [userInfo, setUserInfo] = useState(null);

  useEffect(() => {
    // 立即检查当前store状态
    const currentState = store.getState();
    
    if (currentState.auth.isLoggedIn && currentState.auth.user) {
      setUserInfo(currentState.auth.user);
    } else {
      // 如果store中没有用户信息，尝试从localStorage获取
      const userData = localStorage.getItem("sys_user");
      if (userData) {
        const parsedUserData = JSON.parse(userData);
        setUserInfo(parsedUserData);
        // 同时更新store状态
        store.dispatch({
          type: "LOGIN_SUCCESS",
          payload: { user: parsedUserData },
        });
      }
    }

    // 订阅store变化
    const unsubscribe = store.subscribe(() => {
      const state = store.getState();
      console.log("===========store状态变化========>>>>", state.auth?.user);
      if (state.auth.isLoggedIn && state.auth.user) {
        setUserInfo(state.auth.user);
      } else {
        setUserInfo(null);
      }
    });

    // 清理函数：移除订阅
    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <div className="flex flex-1 h-full flex-col">
      {/* <TitleBar userInfo={userInfo} /> */}
      <div className="flex-1 flex py-2">
        <div className="w-40 h-full ml-2 rounded-lg bg-[#2ac6ff66]">
          <Navigation userInfo={userInfo} />
        </div>
        <div className="flex-1 h-full w-full">{children}</div>
      </div>
    </div>
  );
}
